<template>
    <div class="city">
        <!-- 定位页面 -->
        <input type="text" v-model="searchVal" >
        <div v-for="item in list" @click="goHome(item)" :key="item.uid">
            {{ item.title }}
        </div>
         <div id="allmap"></div>
    </div>
</template>
<script>
import {mapMutations,mapState} from "vuex"
export default {
    data () {
        return {
            searchVal:"",
            map:"",
            list:[]
        }
    },
    computed: {
        ...mapState(["cityInfo"])
    },
    methods: {
        ...mapMutations(["addCity"]), 
        goHome(val){
            this.addCity(val);
            this.$router.push("/home");
        }
    },
    watch: {
        searchVal(){
            var _this = this;
            var options = {
                onSearchComplete: function(results){
                    // 判断状态是否正确
                    if (local.getStatus() == BMAP_STATUS_SUCCESS){
                        console.log(results);
                        _this.list = results.Hr
                        // var s = [];
                        // for (var i = 0; i < results.getCurrentNumPois(); i ++){
                        //     s.push(results.getPoi(i).title + ", " + results.getPoi(i).address);
                        // }
                        // document.getElementById("r-result").innerHTML = s.join("<br/>");
                    }
                }
            };
            var local = new BMap.LocalSearch(this.map, options);
            local.search(this.searchVal);
        }
    },
    mounted () {
        // 如果vuex中有搜索的数据  那么初始化的时候 应该展示vuex的数据 而不是116.404, 39.915
        var map = new BMap.Map("allmap");    // 创建Map实例
        if(this.cityInfo.city){
            // 初始百度地图的中心点
            map.centerAndZoom(new BMap.Point(this.cityInfo.point.lng,this.cityInfo.point.lat), 11);
            var mk = new BMap.Marker(this.cityInfo.point);
                map.addOverlay(mk);
                map.panTo(this.cityInfo.point);
        }else{
            map.centerAndZoom(new BMap.Point(116.404, 39.915), 11);  // 初始化地图,设置中心点坐标和地图级别
            var geolocation = new BMap.Geolocation();
            geolocation.getCurrentPosition(function(r){
                if(this.getStatus() == BMAP_STATUS_SUCCESS){
                    var mk = new BMap.Marker(r.point);
                    map.addOverlay(mk);
                    map.panTo(r.point);

                    
                }
                else {
                    alert('failed'+this.getStatus());
                }        
            },{enableHighAccuracy: true})
        }
        
        
        
        this.map = map;
        
    }
}
</script>
<style lang="scss" scoped>
.city{
    #allmap{
        width: 100%;
        height: 400px;
    }
}
</style>